package com.noodles.mall.filter;

import com.noodles.mall.entity.Menu;
import com.noodles.mall.entity.Role;
import com.noodles.mall.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.SocketUtils;

import java.util.Collection;
import java.util.List;

@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private MenuService menuService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        System.out.println("CustomFilterInvocationSecurityMetadataSource: getAttributes 开始");
        System.out.println("object: "+object);
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        List<Menu> menuList = menuService.selectWithRole();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (Menu menu : menuList) {
            if (antPathMatcher.match(menu.getUrl(), requestUrl)) {
                String[] roleNameList = menu.getRoleList().stream().map(Role::getName).toArray(String[]::new);
                return SecurityConfig.createList(roleNameList);
            }
        }
        System.out.println("CustomFilterInvocationSecurityMetadataSource: getAttributes 结束");
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        System.out.println("CustomFilterInvocationSecurityMetadataSource: getAllConfigAttributes");
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        System.out.println("CustomFilterInvocationSecurityMetadataSource: supports");
        System.out.println("aClass: "+aClass);
        return false;
    }
}
